<template>
  <div class="player-container">
    <template v-for="item in store.remoteStreams" :key="item.getId()">
      <div @click="useToggleBigScreen(item.getId())" class="remote c-p" :id="item.getId()">
        <div v-if="!isFullScreen">
          <span class="change-screen-state">单击大屏/小屏</span>
          <img
            @click.stop="toggleFullScreen(item.getId())"
            class="full-screen"
            src="@/assets/images/full-screen.png"
            alt="全屏"
            title="全屏"
          />
        </div>
        <div class="user-id">用户标识：{{ item.getUserId() }}</div>
      </div>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { inject, nextTick } from 'vue';
import appStore from '@/store/index';
import { useToggleBigScreen } from '@/hooks/useToggleBigScreen';
import { useToggleFullScreen } from '@/hooks/useToggleFullScreen';

const store = appStore();
const $bus = inject('$bus');

// 远端屏幕宽高
const remoteVideoCssConfig = {
  smallWidth: '240px',
  smallHeight: '180px',
  bigWidth: '800px',
  bigHeight: '600px',
};

const { isFullScreen, toggleFullScreen } = useToggleFullScreen();

($bus as any).on('stream-subscribed', async (event: any) => {
  const remoteStream = event.stream;
  const id = remoteStream.getId();
  const userId = remoteStream.getUserId();
  const remoteId = `${id}`;
  store.remoteStreams.push(remoteStream);
  await nextTick();
  remoteStream
    .play(remoteId)
    .then(() => {
      console.log(`RemoteStream play success: [${userId}]`);
    })
    .catch((error: any) => {
      console.error(`RemoteStream play failed: [${userId}], error: ${error.message_}`);
    });

  console.log('stream-subscribed ID: ', id);
});

($bus as any).on('stream-removed', (event: any) => {
  const remoteStream = event.stream;
  const id = remoteStream.getId();
  store.remoteStreams = store.remoteStreams.filter((stream: any) => stream.getId() !== id);
});
</script>

<style lang="scss" scoped>
.player-container {
  width: 800px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
  .remote {
    position: relative;
    width: v-bind('remoteVideoCssConfig.smallWidth');
    height: v-bind('remoteVideoCssConfig.smallHeight');
    margin-right: 26px;
    margin-bottom: 20px;
    .change-screen-state {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      color: #fff;
      z-index: 9;
      display: none;
    }
    .full-screen {
      position: absolute;
      bottom: 5px;
      right: 5px;
      display: none;
      z-index: 99;
    }
    &:hover .change-screen-state,
    &:hover .full-screen {
      display: inline-block;
    }
    .user-id {
      position: absolute;
      top: 0;
      left: 0;
      background-color: rgba(255, 255, 255, 0.5);
      padding: 2px;
      z-index: 10;
    }
  }
}
</style>
